package com.biodiv.community.client;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.biodiv.community.properties.AliyunOssProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class OssClient {

    private final AliyunOssProperties aliyunOssProperties;
    private final IAcsClient client;

    public StsToken generateStsToken() throws ClientException {
        String region = aliyunOssProperties.getRegion();
        String policy = aliyunOssProperties.getPolicy();
        String roleArn = aliyunOssProperties.getRoleArn();
        String bucket = aliyunOssProperties.getBucket();
        Long expireTime = aliyunOssProperties.getExpireTime();

        // 构建请求
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(roleArn);
        request.setRoleSessionName("oss-sts-session");
        request.setDurationSeconds(expireTime);
        request.setPolicy(policy);

        // 获取凭证
        AssumeRoleResponse response = client.getAcsResponse(request);
        AssumeRoleResponse.Credentials credentials = response.getCredentials();

        // 返回结果
        return new StsToken(
                credentials.getAccessKeyId(),
                credentials.getAccessKeySecret(),
                credentials.getSecurityToken(),
                region,
                bucket
        );
    }

    public Long getExpireTime() {
        return aliyunOssProperties.getExpireTime();
    }

    // STS Token 传输对象
    @Data
    @AllArgsConstructor
    public static class StsToken {
        private String accessKeyId;
        private String accessKeySecret;
        private String securityToken;
        private String region;
        private String bucket;
    }
}